package com.gage.print.pdf.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import com.gage.print.pdf.vo.PrintMessage;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.colorspace.PdfDeviceCs;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;

public class PDFUtil {
	private static final NumberFormat NUMBER_FORMAT = new DecimalFormat("000");
	private static final float HEADER_HEIGHT = 50;
	private static final float HEADER_WIDTH = 255;
	private static final int TOP_WHITE_SPACE = 17;
	private static final int FONT_SIZE = 10;
	private static final PageSize DEFAULT_PAGESIZE = PageSize.A4;

	public static List<String> decode_PDF_QRCode(int endX, int endY, byte[] ba) {
		return decode_PDF_QRCode(0, 0, endX, endY, ba, null);
	}

	public static List<String> decode_PDF_QRCode(int endX, int endY, byte[] ba, String basePath) {
		return decode_PDF_QRCode(0, 0, endX, endY, ba, basePath);
	}

	public static List<String> decode_PDF_QRCode(int startX, int startY, int endX, int endY, byte[] ba) {
		return decode_PDF_QRCode(0, 0, endX, endY, ba, null);
	}

	public static List<String> decode_PDF_QRCode(int startX, int startY, int endX, int endY, byte[] ba,
			String basePath) {
		List<String> resultArray = new ArrayList<String>();
		Document document = new Document();
		try {
			document.setByteArray(ba, 0, ba.length, null);
			float scale = 2.0f; // 缩放比例
			float rotation = 0f; // 旋转角度
			for (int i = 0; i < document.getNumberOfPages(); i++) {
				BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,
						Page.BOUNDARY_CROPBOX, rotation, scale);

				BufferedImage result = new BufferedImage(endX - startX, endY - startY, 4);
				for (int x = startX; x < endX; ++x) {
					for (int y = startY; y < endY; ++y) {
						int rgb = image.getRGB(x, y);
						result.setRGB(x - startX, y - startY, rgb);
					}
				}

				if(StringUtils.isNotBlank(basePath)) {
					File file = new File(basePath + File.separator + "word_" + i + ".jpg");
					
					if (file.getParentFile() != null && !file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					
					ImageIO.write(result, "png", file);
				}
				result.flush();

				String resultStr = QRCodeUtil.decode(result);
				resultArray.add(resultStr);
			}
			document.dispose();
		} catch (Exception e) {
			document.dispose();
			e.printStackTrace();
		}

		return resultArray;
	}

	public static void dealWithPDF(File pdfFile, File printFile, PrintMessage printMessage, int currentFileIndex)
			throws IOException {
		PdfReader reader = new PdfReader(pdfFile);
		PdfWriter writer = new PdfWriter(printFile);
		PdfDocument tempPdf = new PdfDocument(reader);
		PdfDocument testPdf = new PdfDocument(writer);

		PdfFont f = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", testPdf);
		testPdf.setDefaultPageSize(DEFAULT_PAGESIZE.rotate());

		Paragraph header = new Paragraph().setFont(PdfFontFactory.createFont(StandardFonts.HELVETICA))
				.setWidth(HEADER_WIDTH).setFontSize(FONT_SIZE).setFont(f).setHeight(HEADER_HEIGHT / 3)
				.setPaddingLeft(FONT_SIZE * 2)
				.setBackgroundColor(Color.makeColor(new PdfDeviceCs.Rgb(), new float[] { 256f, 256f, 256f }))
				.add("姓名：\u3000").add(printMessage.getStudentName()).add("\u3000\u3000\u3000").add("学号：\u3000")
				.add(printMessage.getStudentNo());

		Paragraph header2 = new Paragraph().setFont(PdfFontFactory.createFont(StandardFonts.HELVETICA))
				.setWidth(HEADER_WIDTH).setFontSize(FONT_SIZE).setFont(f).setHeight(HEADER_HEIGHT / 3)
				.setPaddingLeft(FONT_SIZE * 2)
				.setBackgroundColor(Color.makeColor(new PdfDeviceCs.Rgb(), new float[] { 256f, 256f, 256f }))
				.add("学科：\u3000").add(printMessage.getMajorName());

		com.itextpdf.layout.Document doc = new com.itextpdf.layout.Document(testPdf);

		PdfCanvas canvas = null;
		PdfFormXObject page;
		for (int i = 1; i <= tempPdf.getNumberOfPages(); i++) {
			Paragraph header3 = new Paragraph().setFont(PdfFontFactory.createFont(StandardFonts.HELVETICA))
					.setFontSize(FONT_SIZE).setFont(f).setHeight(HEADER_HEIGHT / 3).setPaddingLeft(FONT_SIZE * 2)
					.setWidth(HEADER_WIDTH)
					.setBackgroundColor(Color.makeColor(new PdfDeviceCs.Rgb(), new float[] { 256f, 256f, 256f }))
					.add("试卷编号：\u3000").add(printMessage.getMajorCode())
					.add(NUMBER_FORMAT.format(i + currentFileIndex * tempPdf.getNumberOfPages()));

			page = tempPdf.getPage(i).copyAsFormXObject(testPdf);

			if (i % 2 == 1) {
				canvas = new PdfCanvas(testPdf.addNewPage());
				canvas.addXObject(page, 0, 0);
			} else {
				canvas.addXObject(page, testPdf.getDefaultPageSize().getWidth() / 2, 0);
			}

			testPdf.getPage((i + 1) / 2).setIgnorePageRotationForContent(true);

			doc.showTextAligned(header, (i + 1) % 2 * (testPdf.getDefaultPageSize().getWidth() / 2),
					tempPdf.getPage(i).getPageSize().getTop() - HEADER_HEIGHT / 3 - TOP_WHITE_SPACE, (i + 1) / 2,
					TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0);
			doc.showTextAligned(header2, (i + 1) % 2 * (testPdf.getDefaultPageSize().getWidth() / 2),
					tempPdf.getPage(i).getPageSize().getTop() - 2 * (HEADER_HEIGHT / 3) - TOP_WHITE_SPACE, (i + 1) / 2,
					TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0);
			doc.showTextAligned(header3, (i + 1) % 2 * (testPdf.getDefaultPageSize().getWidth() / 2),
					tempPdf.getPage(i).getPageSize().getTop() - HEADER_HEIGHT - TOP_WHITE_SPACE, (i + 1) / 2,
					TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0);
		}

		doc.close();
		tempPdf.close();
		reader.close();
	}
}
